<template>
  <div>
    <div class="header w-full bg-white h-9">
      <a-button
        type="primary"
        :icon="h(FileTextFilled)"
        class="float-right mr-2"
        @click="handleSave"
        :loading="loading"
        ghost
      >
        保存
      </a-button>
    </div>
    <Repl
      :store="store"
      :showCompileOutput="false"
      :clearConsole="false"
      style="height: calc(100vh - 80px - 36px)"
    />
  </div>
</template>
<script lang="ts" setup>
  import { Repl, ReplStore } from '@vue/repl';
  import { onMounted, h, ref, watch } from 'vue';
  import { FileTextFilled } from '@ant-design/icons-vue';
  import { getWidgetCode, saveWidgetCode } from '/@/api/thingsborad/resources/widgets/widgets';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import '@vue/repl/style.css';
  import { schema } from './index.data';

  const props = defineProps({
    widgetId: {
      type: String,
      default: null,
      required: false,
    },
  });
  const { createMessage } = useMessage();
  const router = useRouter();
  const widgetCode = ref<any>();
  const loading = ref<boolean>(false);

  const store = new ReplStore({
    defaultVueRuntimeURL:
      'https://unpkg.com/@vue/runtime-dom@3.2.45/dist/runtime-dom.esm-browser.js',
  });

  const handleSave = async () => {
    loading.value = true;
    const files = store.getFiles();
    widgetCode.value.descriptor.templateHtml = files['App.vue'];
    widgetCode.value.descriptor.controllerScript = files['import-map.json'];
    await saveWidgetCode(widgetCode.value);
    createMessage.success('保存成功');
    loading.value = false;
  };

  const initView = async (id) => {
    widgetCode.value = await getWidgetCode(id);
    const { descriptor } = widgetCode.value;
    await store.setFiles({
      'App.vue': descriptor.templateHtml,
    });
    store.setImportMap(JSON.parse(descriptor.controllerScript));
  };
  watch(
    () => props.widgetId,
    (nVal) => {
      if (nVal) {
        initView(nVal);
      }
    },
    {
      immediate: true,
    },
  );

  onMounted(async () => {
    const { ruleChainId } = router.currentRoute.value.params;
    if (ruleChainId) {
      initView(ruleChainId);
    }
  });
</script>
